package jp.wug.samples.cart;

import com.google.inject.servlet.SessionScoped;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

public class Models {
    public static class Product {
        long id;
        String name;

        public Product(long id, String name) {
            this.id = id;
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public String getKey() {
            return Long.toString(id);
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof Product) {
                Product product = (Product) obj;
                return id == product.id && name.equals(product.name);
            }
            return false;
        }

        @Override
        public int hashCode() {
            return toString().hashCode();
        }

        @Override
        public String toString() {
            return id + ": " + name;
        }
    }

    @SessionScoped
    public static class Cart {
        Map<String, CartItem> items = new LinkedHashMap<String, CartItem>();

        void add(Product product) {
            CartItem item = items.get(product.getKey());
            if (item == null) {
                item = new CartItem(product);
                items.put(item.getProduct().getKey(), item);
            } else {
                item.setCount(item.getCount() + 1);
            }
        }

        Collection<CartItem> getItems() {
            return items.values();
        }

        CartItem getItem(String key) {
            return items.get(key);
        }
    }

    public static class CartItem {
        Product product;
        int count;

        public CartItem(Product product) {
            this.product = product;
            this.count = 1;
        }

        public Product getProduct() {
            return product;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            if (count <= 0) {
                throw new OutOfRangeException(count + " < 1");
            }
            this.count = count;
        }

        public String getName() {
            return product.getName();
        }
    }
}
